<template>
    <div class="attribute-wrapper">
        <DataGrid
            :auto-load="autoLoad"
            border
            ref="tableRef"
            :showSelection="detailData?.enabled"
            @selection-change="handleSelectionChange"
        >
            <template #toolbar-search>
                <div class="query-from-box">
                    <el-form :model="queryData">
                        <el-form-item>
                            <el-input v-model="queryData.attributeName" placeholder="属性名称/标识符" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="queryData.showName" placeholder="所属设备/组件" clearable />
                        </el-form-item>
                        <el-form-item style="width: 330px">
                            <el-date-picker
                                v-model="queryData.lastTime"
                                type="datetimerange"
                                unlink-panels
                                range-separator="-"
                                start-placeholder="更新时间起"
                                end-placeholder="更新时间止"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="queryData.dataRange" placeholder="数据范围" clearable>
                                <el-option v-for="(value, key) in DataRange" :label="value" :key="key" :value="key" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <template #toolbar-operation>
                <el-button
                    v-if="detailData?.enabled"
                    type="primary"
                    :disabled="!(readSelectId && readSelectId.length)"
                    @click="onRead(readSelectId)"
                    >读取</el-button
                >
                <el-button
                    v-if="detailData?.enabled"
                    type="primary"
                    :disabled="!(issueSelect && issueSelect.length)"
                    @click="onIssue(issueSelect)"
                    >下发</el-button
                >
                <el-button type="primary" @click="onHistory">历史</el-button>
            </template>
            <el-table-column type="index" label="序号" width="60" align="center" show-overflow-tooltip fixed />
            <el-table-column label="属性名称" show-overflow-tooltip fixed>
                <template #default="{ row }">
                    <div class="table-item-name">
                        <span>{{ row.displayName }}</span>
                        <el-tooltip v-if="row.helpText" :content="row.helpText" placement="top">
                            <el-icon size="14px"><InfoFilled /></el-icon>
                        </el-tooltip>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="attributeName" label="标识符" show-overflow-tooltip />
            <el-table-column prop="showName" label="所属设备/组件" show-overflow-tooltip />
            <el-table-column label="设定值">
                <template #default="{ row }">
                    <span
                        :style="{
                            color: row.setValue
                                ? row.dataType == 'NUMBER'
                                    ? row.value == row.setValue
                                        ? ''
                                        : '#F56C6C'
                                    : row.value === row.setValue
                                      ? ''
                                      : '#F56C6C'
                                : ''
                        }"
                    >
                        {{ row.setValue }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="当前值">
                <template #default="{ row }">
                    <span
                        :style="{
                            color: row.setValue
                                ? row.dataType == 'NUMBER'
                                    ? row.value == row.setValue
                                        ? ''
                                        : '#F56C6C'
                                    : row.value === row.setValue
                                      ? ''
                                      : '#F56C6C'
                                : ''
                        }"
                    >
                        {{ row.value }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="lastTime" label="最新更新时间" show-overflow-tooltip />
            <el-table-column label="操作" width="90" fixed="right" v-if="detailData?.enabled">
                <template #default="{ row }">
                    <el-button
                        link
                        type="primary"
                        v-if="(row.rwFlag == 'READWRITE' || row.rwFlag == 'WRITE') && row.componentEnable"
                        @click="onIssue(row)"
                    >
                        下发
                    </el-button>
                </template>
            </el-table-column>
        </DataGrid>
    </div>
</template>
<script setup lang="ts">
import { IoTDeviceService } from '@great/services';
import { InfoFilled } from '@element-plus/icons-vue';
import { DataGrid, type DataGridInstance } from '@great/components';
import AttributeHistoryModal from './AttributeHistoryModal.vue';
import AttributeIssueModal from './AttributeIssueModal.vue';
import { showPopupBox } from '@great/utils';

const props = defineProps<{
    detailData?: Record<string, any>;
}>();

enum DataRange {
    EQ = '设定值 = 当前值',
    NEQ = '设定值 != 当前值'
}

// 查询条件
const queryData = ref({
    lastTime: '',
    attributeName: '',
    showName: '',
    dataRange: ''
});
const tableRef = useTemplateRef<DataGridInstance>('tableRef');
const tableData = ref<Array<any>>([]);
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await IoTDeviceService.getThingAttribute({
            proDeviceNo: props.detailData?.deviceNo,
            productObject: props.detailData?.objectName
        });
        tableData.value = res.data;
        const targetTableData = queryTable(tableData.value, current, size);
        return { data: targetTableData.list, total: targetTableData.total };
    }
});
type Attrs = {
    attributeName: String;
    deviceNo: String;
    objectName: String;
    value?: String;
};
// 表格勾选数据
const tableSelect = ref<Record<string, any>[]>([]);
const issueSelect = ref<Record<string, any>[]>([]);
const readSelectId = ref<Array<Attrs>>([]);

// 表格勾选
const handleSelectionChange = (val: Record<string, any>[]) => {
    tableSelect.value = val;
    issueSelect.value = [];
    readSelectId.value = [];
    val.forEach((item: any) => {
        if (item.componentEnable) {
            // 组件启用，标识是：读写/只读，可下发
            if (item.rwFlag == 'READWRITE' || item.rwFlag == 'READ') {
                readSelectId.value.push({
                    attributeName: item.attributeName,
                    deviceNo: item.deviceNo,
                    objectName: item.objectName
                });
            }
            // 组件启用，标识是：读写/只写，可下发
            if (item.rwFlag == 'READWRITE' || item.rwFlag == 'WRITE') {
                issueSelect.value.push(item);
            }
        }
    });
};

// 读取
const onRead = async (attrs: Array<Attrs>) => {
    await IoTDeviceService.attributeRead({
        proDeviceNo: props.detailData?.deviceNo,
        productObject: props.detailData?.objectName,
        attrs
    });
    ElNotification({
        title: '读取成功！',
        type: 'success'
    });
    tableRef.value?.refresh();
};
// 下发
const onIssue = (rowList: Array<Record<string, any>>) => {
    showPopupBox(AttributeIssueModal, {
        rowList: Array.isArray(rowList) ? rowList : [rowList],
        tableSelect: Array.isArray(rowList) ? tableSelect.value : undefined,
        deviceDetail: props.detailData as Record<string, any>,
        callBack: tableRef.value?.refresh as () => Promise<void>
    });
};
// 历史
const onHistory = () => {
    showPopupBox(AttributeHistoryModal, {
        deviceDetail: props.detailData as Record<string, any>
    });
};

// 表格数据筛选
const queryTable = (sourceData: Array<any>, current: number, size: number): { list: Array<any>; total: number } => {
    let targetData: Array<any> = JSON.parse(JSON.stringify(sourceData));
    // 过滤逻辑
    if (queryData.value.attributeName) {
        targetData = targetData.filter(item => {
            return (
                item.displayName.toLowerCase().includes(queryData.value.attributeName.toLowerCase()) ||
                item.attributeName.toLowerCase().includes(queryData.value.attributeName.toLowerCase())
            );
        });
    }
    if (queryData.value.showName) {
        targetData = targetData.filter(item =>
            item.showName.toLowerCase().includes(queryData.value.showName.toLowerCase())
        );
    }
    if (queryData.value.lastTime) {
        targetData = targetData.filter(item => {
            if (!item.lastTime) return false;
            const itemTime = new Date(item.lastTime).getTime();
            const startTime = new Date(queryData.value.lastTime[0]).getTime();
            const endTime = new Date(queryData.value.lastTime[1]).getTime();
            return itemTime >= startTime && itemTime <= endTime;
        });
    }
    if (queryData.value.dataRange) {
        if (queryData.value.dataRange == 'EQ') {
            targetData = targetData.filter(item => {
                if (item.dataType == 'NUMBER') {
                    return item.value == item.setValue;
                } else {
                    return item.value == item.setValue;
                }
            });
        } else if (queryData.value.dataRange == 'NEQ') {
            targetData = targetData.filter(item => {
                if (item.dataType == 'NUMBER') {
                    return item.value != item.setValue;
                } else {
                    return item.value != item.setValue;
                }
            });
        }
    }
    // 分页逻辑：计算起始索引和结束索引
    const startIndex = (current - 1) * size;
    const endIndex = startIndex + size;
    return { list: targetData.slice(startIndex, endIndex), total: targetData.length };
};
</script>
<style scoped lang="scss">
.attribute-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-name {
            display: flex;
            align-items: center;
            .el-tooltip__trigger {
                margin-left: 5px;
            }
        }
    }
}
</style>
